﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.UI.Blog.NodeTypes;
using Medianamik.Core.Querying;
using Medianamik.UI.Controls;
using Telerik.Web.UI;
using Medianamik.UI.Blog.Logic;

namespace Medianamik.UI.Blog
{
    public partial class blogList : BaseModuleListPage
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            InitTypeSelector();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            bctFilAriane.NavigateParent += bctFilAriane_NavigateParent;

            if (!IsPostBack)
            {
                rptNodeTypeUrls.DataSource = CommonData.BlogTypesUrl;
                rptNodeTypeUrls.DataBind();

                var parentId = new Guid();
                if (Core.Sugar.StringHelper.IsGuid(Request["parentId"], out parentId))
                    ParentNodeId = parentId;

                LoadBreadcrumbs();
            }

            SetRadWindowUrl();
        }

        protected void Grid_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == String.Empty)
            {
                ParentNodeId = (Guid)(e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"];
                Grid.Rebind();
                LoadBreadcrumbs();
                SetRadWindowUrl();
            }
        }

        void bctFilAriane_NavigateParent(object sender, NavigateParentEventArgs e)
        {
            ParentNodeId = new Guid(e.ItemID);
            Grid.Rebind();
            SetRadWindowUrl();
            GridUpdatePanel.Update();
            LoadBreadcrumbs();
        }

        protected void Grid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.DataItem != null)
            {
                var editButton = e.Item.FindControlR("editButton") as LockButton;
                var currentItem = e.Item.DataItem as Node;

                if (editButton != null)
                {
                    if (CommonData.BlogTypesUrl.ContainsKey(currentItem.NodeTypeID))
                        editButton.NavigateUrl = String.Format("{0}?{1}={2}",
                                                               CommonData.BlogTypesUrl[currentItem.NodeTypeID],
                                                               NodeIdParamName, currentItem.ID);
                    else
                        editButton.NavigateUrl = String.Format("{0}?{1}={2}&typeid={3}",
                                                               "editCustomType.aspx",
                                                               NodeIdParamName, currentItem.ID, currentItem.NodeTypeID);
                }

                if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
                {
                    var gridItem = (GridDataItem) e.Item;
                    if (gridItem != null)
                        if (currentItem.IsDraft && currentItem.IsVersioned)
                            gridItem.CssClass = "rgRow ElementBrouillon";
                }
            }
        }

        protected override void OnCultureChanged(CultureChangedEventArgs e)
        {
            ReloadAll();
        }

        protected override string ReturnUrl
        {
            get
            {
                return "/medianamik/blog/blogList.aspx";
            }
        }

        protected override Guid? ParentNodeId
        {
            get { return (Guid?)ViewState["ParentNodeId"] ?? BaseBlog.ModuleParentId; }
            set { ViewState["ParentNodeId"] = value; _parentNode = null; }
        }

        private Node _parentNode;
        protected override Node ParentNode
        {
            get { return _parentNode ?? (_parentNode = NodeManager.GetNode(ParentNodeId.GetValueOrDefault())); }
        }

        private void ReloadAll()
        {
            ReloadGrid();
            ReloadBreadcrumbTrail();
        }

        private void ReloadGrid()
        {
            Grid.Rebind();
            mainUpdatePanel.Update();
        }

        private void ReloadBreadcrumbTrail()
        {
            LoadBreadcrumbs();
            breadcrumbUpdatePanel.Update();
        }

        private void InitTypeSelector()
        {
            var typeSelectorWindow = new BaseModalWindow { ID = "TypeSelectorWindow" };

            if (!IsPostBack)
            {
                typeSelectorWindow.ID = "TypeSelectorWindow";
                typeSelectorWindow.OnClientClose = "onNodeTypeSelected";
                typeSelectorWindow.IconUrl = "/Medianamik/images/Icones/Ico_AjoutPage.gif";
                typeSelectorWindow.ReloadOnShow = true;
                typeSelectorWindow.Width = Unit.Pixel(400);
                typeSelectorWindow.Height = Unit.Pixel(200);
            }

            MyWindowManager.Windows.Add(typeSelectorWindow);
        }

        protected  override void LoadBreadcrumbs()
        {
            bctFilAriane.Breadcrumbs = ParentNode.Breadcrumbs.Skip(1);
            bctFilAriane.DataBind();
            breadcrumbUpdatePanel.Update();
        }

        private void SetRadWindowUrl()
        {
            lnkAddNode.NavigateUrl = String.Concat(Pages.TypeSelectorWindow,
                GetParentNodeParam("?"));

            addNodeUpdatePanel.Update();
        }

        protected string GetParentNodeParam(string pParamDelimiter)
        {
            return String.Format("{0}{3}={1}&{4}={2}", 
                pParamDelimiter, ParentNodeId, BaseBlog.TypeId, 
                DefaultParamNames.ParentNodeID, DefaultParamNames.LimitToParentTypeId);
        }

        protected override void GridNeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            Grid.DataSource = new Query()
                                .Where(q => q.ParentID, Comparison.Equal, ParentNodeId)
                                .OrderBy(q => q.Position)
                                .Execute();
        }

        protected override RadGrid Grid
        {
            get { return blogContainersGrid; }
        }

        protected override GridActionOptions GridActionOptions
        {
            get
            {
                return GridActionOptions.All;
            }
        }

        protected override GridOptions GridOptions
        {
            get
            {
                return GridOptions.NavigateName;
            }
        }

        protected override UpdatePanel GridUpdatePanel
        {
            get { return mainUpdatePanel; }
        }

        protected override string ManagementURL
        {
            get { return "editBlogContainer.aspx"; }
        }
    }
}